package com.gitee.feizns.quickstart.itext7;

import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;

import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
import java.util.function.Consumer;

/**
 * itext7 实用程序
 * @author feizns
 * @since 2024/12/2
 */
public class Itext7s {

    /**
     * PDF 文档
     * @return {@link PdfDocument}
     */
    public static PdfDocument pdfDocument(OutputStream os) {
        return new PdfDocument(new PdfWriter(os));
    }

    /**
     * PDF 编写器
     * 写入桌面示例：
     * <pre>{@code
     *     @SneakyThrows
     *     public static void main(String[] args) {
     *         try ( FileOutputStream stream = new FileOutputStream("C:\\Users\\28293\\Desktop\\tmp.pdf")) {
     *             stream.write(Itext7s.pdf(doc -> doc.add(new Paragraph("HELLO WORLD"))));
     *             stream.flush();
     *         }
     *     }
     * }</pre>
     * @param documentConsumer 文档使用者
     * @return {@link byte[]}
     */
    public static byte[] document(Consumer<Document> documentConsumer) {
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        try (Document document = new Document(pdfDocument(os)) ) {
            documentConsumer.accept(document);
        }
        return os.toByteArray();
    }

}
